<template>
  <div>
    <el-button
      slot="append"
      icon="el-icon-more"
      @click="dialogTableVisible=true"
      size="mini"
      >单击选择</el-button>
    <template v-if="showSelectionSlot">
      <el-popover
        v-if="allSelection.length>0"
        placement="right"
        width="400"
        trigger="hover">
        <el-tag
          v-for="(selection,index) in allSelection"
          :key="index"
          closable
          :disable-transitions="false"
          @close="handleRemoveTag(selection)">
          {{selection[displayKey]?selection[displayKey]:"未知"}}
        </el-tag>
        <el-button slot="reference" type="text" size="mini">{{showContent ? showContent : "共选中"+allSelection.length+"条记录"}}
          <i class="el-icon-error" type="error" @click="handleClearAll"></i>
        </el-button>
      </el-popover>
    </template>

    <!-- 选中结果回显插槽 -->
    <slot name="selectionSlot"></slot>

    <!-- dialog -->
    <el-dialog
      :title="fld.title"
      :visible.sync="dialogTableVisible"
      :width="width"
      @open="handleOpen">

      <comp-table
        :cols="columns"
        :action="fld.action"
        ref="table"
        height="290"
        @select="handleUserSelect"
        @select-all="handleUserSelectAll"
        >
        <!-- 左上角插槽-搜索 -->
        <template slot="leftTopSlot">
          <div style="width:180px;float:left;margin-bottom:5px;">
            <el-input placeholder="关键字"  size="mini" v-model="key">
              <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
            </el-input>
          </div>
        </template>

        <!-- 左下角插槽-分页 -->
        <template slot="leftBottomSlot">
          <div style="float:left; margin-top:5px;" >
            <div style="float:left;">
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[20,50, 100, 200]"
                :page-size="pagesize"
                layout="total, sizes, prev, pager, next"
                :total="total"
                background
              ></el-pagination>
            </div>
            <!-- 分页后的文字说明 -->
            <!--<span style="float:left;margin-top:9px;" v-html="textAfterPage"></span> -->
          </div>
        </template>
      </comp-table>

      <div slot="footer" class="dialog-footer" style="clear:both;">
        <el-button type="primary" @click="handleSelect">确 定</el-button>
        <el-button @click="dialogTableVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script type="text/javascript">
  define(['vue','_vue!pathComponent/comp-popup-select'],function(vue,compSelect){
    //弹出选择,多选,比如多个产品
    //回显效果变化太多,不进行封装,故只做一个触发弹出的多选按钮,
    return vue.component('comp-popup-multi-select',{
      template: template,
      extends: compSelect,
      // props:['fld','value'],
      data:function(){
        return {
          columns: {
            // 'date':{'text':'日期','width':200},
            // 'name':{'text':'姓名','width':200},
            // 'address':{'text':'地址','width':300},
          },
          // rows: [
          //   // {
          //   //   date: '2016-05-02',
          //   //   name: '王小虎',
          //   //   address: '上海市普陀区金沙江路 1518 弄'
          //   // }
          // ],
          //是否支持选中记录
          multiSelect:true,
          //本页选中记录
          multipleSelection:[],
          //其他页选中记录
          otherSelection:[],
          //所有选中记录,可能跨页
          allSelection:this.value||[],
          //获取数据的url
          action:this.fld.action,
          //参数:其中可能包括从open方法中传入的参数,搜索参数,分页参数
          params:{},
          //搜索关键字
          key:'',
          //记录的主键记录
          rowKey: this.fld.rowKey ? this.fld.rowKey : 'id',
          //displayKey,displayText
          //对话框是否显示
          dialogTableVisible:false,
          //分页参数
          currentPage:1,
          pagesize:20,
          total:400,//记录总数
          showContent:'',
          //远程载入次数
          loadTimes:0,
          //是否显示结果,如果存在用户自定义插槽,不显示
          showSelectionSlot:true,
          //选中结果中,用来进行回显选中结果的字段.
          displayKey:this.fld.displayKey,

        };
      },
      methods:{
        //本页选中和其他选中进行join
        _joinCurOther : function() {
          var allSelection = [];
          for(var key in this.multipleSelection) {
            allSelection.push(this.multipleSelection[key]);
          }
          for(var key in this.otherSelection) {
            allSelection.push(this.otherSelection[key]);
          }
          return allSelection;
        },
        //通过ajax请求从服务器获得数据
        _getRows : function() {
          var url = this.action;
          if(url=='' || url==undefined) {
            alert('pop-select 组件未定义action参数');
            return false;
          }
          //本页选中和其他选中进行join
          if(this.loadTimes>0) {
            this.allSelection = this._joinCurOther();
          }

          this.params.pagesize = this.pagesize;
          this.params.currentPage = this.currentPage;
          this.params.key = this.key;
          // var param= {pagesize:this.pagesize,currentPage:this.currentPage};
          var _this = this;
          this.$http.post(url, this.params)
          .then(function (response) {
            var cols = _this._formatColumns(response.data.columns);
            var rows = _this._formatRows(response.data.rows);
            _this.total = response.data.total;
            _this.$refs.table.columns = response.data.columns;
            _this.$refs.table.rows = rows;
            _this.loadTimes++;
            // dump(_this);

            //设置默认选中状态,
            //无法在mounted或者open事件中定义,因为那时rows还没有准备好,所以不能正确选择
            //使用nexttick是因为dom未渲染时,方法不会起作用.将回调延迟到下次 DOM 更新循环之后执行
            if(_this.allSelection.length>0) {
              //拆分成本页和非本页
              //1,给all加上key
              var tempAll = [];
              for(var key in _this.allSelection) {
                var item = _this.allSelection[key];
                tempAll[item.id] = item;
              }

              //2,分解
              var arrIn=[];
              var arrOut=[];
              rows.forEach((item,key)=>{
                // dump(key);
                if (tempAll.hasOwnProperty(item.id)) {
                  arrIn[item.id] = item;
                }
              })
              for(var key in tempAll) {
                if (!arrIn.hasOwnProperty(key)) {
                  arrOut.push(tempAll[key]);
                }
              }
              _this.multipleSelection = [];
              for(var key in arrIn) {
                _this.multipleSelection.push(arrIn[key]);
              }
              _this.otherSelection = arrOut;

              _this.$nextTick(function(){
                _this.multipleSelection.forEach((item,key)=>{
                  _this.$refs.table.$refs.table.toggleRowSelection(item,true);
                });
              });
            }
          })
          .catch(function (error) {
            dump(error);
          });
        },
        //删除选中项触发
        handleRemoveTag : function(selection) {
          var index = this.allSelection.indexOf(selection);
          this.allSelection.splice(index,1);

          index = this.multipleSelection.indexOf(selection);
          if(index>-1) {
            var rowsRemoved = this.multipleSelection.splice(index,1);
            this.$refs.table.$refs.table.toggleRowSelection(rowsRemoved[0],false);
          }

          index = this.otherSelection.indexOf(selection);
          if(index>-1) {
            this.otherSelection.splice(index,1);
          }
        },
        //清除全部
        handleClearAll : function() {
          this.$confirm('确认清除所有选中记录吗？', '确认信息', {
            distinguishCancelAndClose: true,
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type:'warning',
          }).then(()=>{
            this.allSelection=[];
            this.multipleSelection=[];
            this.otherSelection=[];
          });

        },

        //用户选中某航触发
        handleUserSelect(selection,row) {
          this.multipleSelection = selection;
          //如果是取消某行选中,从allselect中删除,否则加入
          if(this.multipleSelection.indexOf(row)==-1) {
            for(var i=0;this.allSelection[i];i++) {
              if(this.allSelection[i][this.rowKey]==row[this.rowKey]) {
                this.allSelection.splice(i,1);
                break;
              }
            }
          } else {
            this.allSelection.push(row);
          }
        },
        //用户全选触发
        handleUserSelectAll(selection) {
          this.multipleSelection = selection;
        },
        //点击确认后回调
        handleSelect : function(){
          this.dialogTableVisible = false;
          this.allSelection = this._joinCurOther();
          this.$emit('input',this.allSelection);

          var key = `${this.fld.name}:select`;
          if(this.$root.callbacks[key]) {
            this.$root.callbacks[key].apply(this,[this.allSelection]);
          }
        },
      },
      mounted: function() {
        //如果存在选中结果显示插槽,才显示
        if(this.$slots.selectionSlot) this.showSelectionSlot=false;
      }
    });
  });
</script>